package com.dl.blog.controller;

import com.dl.blog.entity.VisitRecordDTO;
import com.dl.blog.service.VisitService;
import com.dl.dlcommon.utils.result.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author DL
 * @create 2025-07-07 下午9:45
 */
@RestController
@RequestMapping("/api/visit")
public class VisitController {

    @Autowired
    private VisitService visitService;

    /**
     * 记录页面访问
     */
    @PostMapping("/record")
    public Result<?> recordVisit(@RequestBody VisitRecordDTO recordDTO, HttpServletRequest request) {
        // 获取客户端IP
        String clientIp = getClientIp(request);

        // 获取User-Agent
        String userAgent = request.getHeader("User-Agent");

        String referer = request.getHeader("Referer");
        recordDTO.setReferer(referer);
        // 记录访问
        visitService.recordVisit(recordDTO, clientIp, userAgent);

        return Result.ok();
    }

    // 获取客户端真实IP
    private String getClientIp(HttpServletRequest request) {
        String xffHeader = request.getHeader("X-Forwarded-For");
        if (xffHeader == null) {
            return request.getRemoteAddr();
        }
        return xffHeader.split(",")[0];
    }
}
